package com.cy.store.service.impl;

import com.cy.store.entity.Cart;
import com.cy.store.entity.Favor;
import com.cy.store.entity.Product;

import com.cy.store.mapper.FavorMapper;
import com.cy.store.service.ICartService;
import com.cy.store.service.IFavorService;
import com.cy.store.service.IProductService;
import com.cy.store.service.ex.CartNotFoundException;
import com.cy.store.service.ex.InsertException;
import com.cy.store.vo.CartVO;
import com.cy.store.vo.FavorVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class FavorServiceImpl implements IFavorService {
    @Autowired
    private FavorMapper favorMapper;
    @Autowired
    private IProductService productService;

    @Override
    public void addToFavor(Integer uid, Integer pid,String username) {
        // 根据参数pid和uid查询购物车中的数据
        Favor result = favorMapper.findByUidAndPid(uid, pid);
        Date now = new Date();
        // 判断查询结果是否为null
        if (result == null) {
            // 是：表示该用户并未将该商品添加到购物车
            // 创建Cart对象
            Favor favor = new Favor();
            // 封装数据：uid,pid,amount
            favor.setUid(uid);
            favor.setPid(pid);
            // 调用productService.findById(pid)查询商品数据，得到商品价格
            Product product = productService.findById(pid);
            // 封装数据：price
            favor.setPrice(product.getPrice());
            favor.setTitle(product.getTitle());
            favor.setImage(product.getImage());
            // 封装数据：4个日志
            favor.setCreatedUser(username);
            favor.setCreatedTime(now);
            favor.setModifiedUser(username);
            favor.setModifiedTime(now);
            Integer rows = favorMapper.insert(favor);
            if (rows != 1) {
                throw new InsertException("收藏商品数据时出现未知错误，请联系系统管理员");
            }
        } else {
            // 否：表示该用户的收藏中已有该商品
                throw new InsertException("已收藏");
        }
    }

    @Override
    public Integer delFavorItem(Integer fid, Integer uid) {
        Integer result = favorMapper.delete(fid,uid);//调用jdbc操作数据库
        // 判断查询结果是否为null
        if (result == null) {
            // 是：抛出CartNotFoundException
            throw new CartNotFoundException("尝试取消收藏的数据不存在");
        }
        return result;
    }

    @Override
    public List<FavorVO> getVOByUid(Integer uid) {
        return favorMapper.findVOByUid(uid);
    }

//    商品详情页判断该商品是否被收藏

    @Override
    public Favor judgeExist(Integer pid, Integer uid) {
        Favor result = favorMapper.findByUidAndPid(uid, pid);
//        System.out.println("查询该商品是否收藏"+result);
        return  result;
    }
}
